package com.hxzy.yygh.user.api;

import com.alibaba.fastjson.JSONObject;
import com.hxzy.yygh.common.helper.JwtHelper;
import com.hxzy.yygh.common.result.Result;
import com.hxzy.yygh.model.user.UserInfo;
import com.hxzy.yygh.user.service.UserInfoService;
import com.hxzy.yygh.user.utils.ConstantPropertiesUtil;
import com.hxzy.yygh.user.utils.HttpClientUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "微信登录模块")
@Controller
@RequestMapping("/api/ucenter/wx")
public class WeixinApiController {
    @Autowired
    private UserInfoService userInfoService;

    //生成微信扫描二维码
    @ApiOperation(value = "生成微信二维码接口")
    @GetMapping("getLoginParam")
    @ResponseBody
    public Result getQrConnect(){
        Map<String, Object> map = new HashMap<>();
        //1.封装应用唯一标识
        map.put("appid", ConstantPropertiesUtil.WX_OPEN_APP_ID);

        //2.封装应用授权作用域
        map.put("scope", "snsapi_login");

        //3.封装回调网址
        String wxOpenRedirectUrl = ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL;
        try {
            wxOpenRedirectUrl  = URLEncoder.encode(wxOpenRedirectUrl, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        map.put("redirect_uri", wxOpenRedirectUrl);

        //4.封装回调的状态
        map.put("state", System.currentTimeMillis() + "");

        return Result.ok(map);
    }

    //2 回调的方法，得到扫描人信息
    @GetMapping("callback")
    public String callback(String code,String state){
        //拼接请求参数和路径,%s 是占位符
        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");
        //依次将appid、appsecret、code填入占位符
        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                code);

        try {
            //使用httpclient请求这个地址,微信开放平台那边会返回一个信息数据给我们
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);

            //从返回字符串获取 openid 和 access_token
            JSONObject jsonObject = JSONObject.parseObject(accessTokenInfo);
            String access_token = jsonObject.getString("access_token");
            String openid = jsonObject.getString("openid");

            //根据openid,获取用户信息
            UserInfo userInfo = userInfoService.selectWxInfoOpenId(openid);

            if (userInfo == null){

                //拼接请求参数和路径
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, access_token, openid);

                //根据微信请求用户信息的地址，返回扫描人信息
                String resultInfo = HttpClientUtils.get(userInfoUrl);

                //根据扫描人信息，获取里面的昵称和用户头像
                JSONObject resultUserInfoJson = JSONObject.parseObject(resultInfo);
                String nickname = resultUserInfoJson.getString("nickname");
                String headimgurl = resultUserInfoJson.getString("headimgurl");

                //封装用户参数，存入我们自己的数据库中
                userInfo = new UserInfo();
                userInfo.setNickName(nickname);
                userInfo.setStatus(1);
                userInfo.setOpenid(openid);
                userInfoService.save(userInfo);
            }

            //①封装用户name
            Map<String, String> map = new HashMap<>();
                //获取用户的名字
                String name = userInfo.getName();

                //如果没有名字，则用昵称作为名字
                if (StringUtils.isEmpty(name)){
                    name = userInfo.getNickName();
                }
                //如果昵称也没有的话，就用手机号作为名字
                if (StringUtils.isEmpty(name)){
                    name = userInfo.getPhone();
                }
                //将name存入map集合
                map.put("name", name);

            //②封装openid--后面需要根据扫码人是否包含openid，决定是否绑定手机号
                //先判断userinfo中是否有手机号
                if(StringUtils.isEmpty(userInfo.getPhone())){
                    //将openid存入map集合
                    map.put("openid", userInfo.getOpenid());
                }else {
                    //将openid 变为null
                    map.put("openid", "");
                }

            //③封装token
                //利用工具类，生成一个用户的token
                String token = JwtHelper.createToken(userInfo.getId(), name);
                //将token存入map集合中
                map.put("token", token);

            //重定向到前端对应页面，并且携带参数
            return "redirect:" + ConstantPropertiesUtil.YYGH_BASE_URL + "/weixin/callback?token="+map.get("token")+"&openid="+map.get("openid")+"&name="+URLEncoder.encode((String)map.get("name"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
